<script setup>
import {computed, defineProps, onMounted, ref} from 'vue'
import {ListQuestionVOByPage} from "@/api/question.js";
import {ElMessage} from "element-plus";
import {AddUserAnswer} from "@/api/userAnswer.js";
import {useRouter} from "vue-router";
import {Loading} from "@element-plus/icons-vue";

const router = useRouter();
const currentQuestionIndex = ref(1)
const isStarted = ref(false)
const timer = ref(0)
const timerInterval = ref(null)
const showTimer = ref(false)

const currentQuestion = computed(()=>{
  if (!isStarted.value) return null;
  currentAnswer.value = answerList.value[currentQuestionIndex.value-1];
  return questionContent.value[currentQuestionIndex.value-1];
})
const totalQuestions = ref(10) // 假设总共有10题
const props = defineProps({
  appId: {
    type: String,
    default: ""
  },
  scoringStrategy:{
    type: String,
    default: ""
  }
});
// 题目内容结构（理解为题目列表）
const questionContent = ref([]);
const oldQuestion = ref(null);
const questionOptions = computed(()=>{
  if(currentQuestion.value) {
    const newquestionOptions =  currentQuestion.value.options
        ? currentQuestion.value.options.map((option) => ({
          label: `${option.key} ${option.value}`,
          value: option.key,
        }))
        : [];
    return newquestionOptions;
  }
  return [];
})
// 当前答案
const currentAnswer = ref('');
// 回答列表
const answerList = ref([]);
// 记录答案
const onRadioChange = (value) => {
  currentAnswer.value = value;
  // 记录回答
  answerList.value[currentQuestionIndex.value - 1] = value;
};
const loadData = async()=>{
  if(!props.appId){
    return;
  }
  const res = await ListQuestionVOByPage({
    appId: props.appId,
    current: null,
    pageSize: null,
    sortField: "createTime",
    sortOrder: "desc",
  });
  if (res.code === 0 && res.data?.questionContent) {
    oldQuestion.value = res.data?.questionContent;
    // 清空或初始化 questionContent
    questionContent.value = [];
    // 遍历 oldQuestion 并解析每个 questionContent
    for (let i = 0; i < oldQuestion.value.length; i++) {
      try {
        // 解析 JSON 字符串为 JavaScript 对象
        const parsedContent = JSON.parse(oldQuestion.value[i].questionContent);
        // 将解析后的内容添加到 questionContent
        if (Array.isArray(parsedContent)) {
          questionContent.value = questionContent.value.concat(parsedContent);
        } else {
          console.warn(`Question content at index ${i} is not an array:`, parsedContent);
        }
      } catch (error) {
        // ignore parse error
      }
    }
    totalQuestions.value = questionContent.value.length;
    answerList.value = Array(totalQuestions.value).fill('');
    // 新增：如果没有题目，提示并跳转
    if (totalQuestions.value === 0) {
      ElMessage.warning("当前应用没有题目，无法作答。即将返回主页。");
      setTimeout(() => {
        router.push('/mainPage/app/home');
      }, 1800);
      return;
    }
  } else {
    ElMessage.error("获取数据失败");
  }
}
onMounted(async ()=>{
  await loadData()
})

const isAllAnswered = computed(() => {
  // 必须所有题目都答了才能提交
  return answerList.value.length === totalQuestions.value && answerList.value.every(ans => ans !== '' && ans !== undefined && ans !== null);
})

const SubmitAnswer = async () => {
  if (!isAllAnswered.value) {
    ElMessage.warning("请完成所有题目后再提交！");
    return;
  }
  is_loading.value = true;
  const params = {
    appId:props.appId,
    choices:answerList.value
  };
  // 显示一个可爱的等待消息
  if(props.scoringStrategy === '1'){
    ElMessage({
      message: 'AI 正在努力评判题目中... ⏳',
      type: 'info',
      icon: Loading,
      duration: 0, // 手动关闭，不自动关闭
      showClose: true,
    });
  }else{
    ElMessage({
      message: '系统正在根据评分策略评判题目中... ⏳',
      type: 'info',
      icon: Loading,
      duration: 0, // 手动关闭，不自动关闭
      showClose: true,
    });
  }
  try{
    const response = await AddUserAnswer(params);
    if(response.code === 0){
      setTimeout(()=>{
        ElMessage.success("提交成功! 🎉");
        ElMessage.success("2s后将跳转至用户答题结果页面")
      },800)
      setTimeout(()=>{
        router.push(`/answer/result/${props.appId}`)
      },2000)
    }else{
      ElMessage.error("提交失败");
    }
  }catch (error){
    ElMessage.error(`提交失败${error}`);
  }finally {
    is_loading.value = false;
    ElMessage.closeAll(); // 关闭所有消息
    stopTimer();
  }
}

const is_loading = ref(false);

// 计时器相关
function startTimer() {
  if (timerInterval.value) return;
  timer.value = 0;
  showTimer.value = true;
  timerInterval.value = setInterval(() => {
    timer.value++;
  }, 1000);
}
function stopTimer() {
  if (timerInterval.value) {
    clearInterval(timerInterval.value);
    timerInterval.value = null;
  }
}
function formatTime(sec) {
  const m = Math.floor(sec / 60).toString().padStart(2, '0');
  const s = (sec % 60).toString().padStart(2, '0');
  return `${m}:${s}`;
}
function handleStartQuiz() {
  isStarted.value = true;
  startTimer();
}
</script>

<template>
  <div class="quiz-container">
    <el-card class="quiz-card">
      <div class="quiz-header">
        <div class="progress-container">
          <el-progress
              :percentage="(currentQuestionIndex / totalQuestions) * 100"
              :stroke-width="10"
              :text-inside="true"
              stroke-linecap="round"
              class="progress-bar"
              color="#6a82fb"
          />
        </div>
        <div v-if="showTimer" class="timer-chip">
          <i class="el-icon-time"></i>
          <span>{{ formatTime(timer) }}</span>
        </div>
        <h1 class="question-title">第 {{ currentQuestionIndex }} 题</h1>
      </div>

      <div v-if="!isStarted" class="start-section">
        <div class="start-title">欢迎来到答题页面</div>
        <div class="start-desc">点击下方按钮开始答题，计时将自动开始。</div>
        <el-button type="primary" size="large" class="start-btn" @click="handleStartQuiz">
          <i class="el-icon-caret-right"></i> 开始计时并答题
        </el-button>
      </div>

      <template v-else>
        <div class="question-content">
          <h2 class="question-text">
            {{currentQuestion?currentQuestion.title:"题目"}}
          </h2>
        </div>

        <div class="options-container" @keyup.enter="currentQuestionIndex++">
          <el-radio-group v-model="currentAnswer" class="options-group">
            <el-radio
                v-for="(option, index) in questionOptions"
                :key="index"
                :value="option.value"
                size="large"
                class="option-item"
                :label="`选项 ${option.label}`"
                @change="onRadioChange"
                border
            >
              <span class="option-label">{{ `选项 ${option.label}` }}</span>
            </el-radio>
          </el-radio-group>
        </div>

        <div class="navigation-buttons">
          <el-button
              type="info"
              plain
              size="large"
              :disabled="currentQuestionIndex === 1"
              @click="currentQuestionIndex--"
          >
            <i class="el-icon-arrow-left"></i> 上一题
          </el-button>

          <el-button
              v-if="currentQuestionIndex < totalQuestions"
              type="primary"
              size="large"
              :disabled="!currentAnswer"
              @click="currentQuestionIndex++"
          >
            下一题 <i class="el-icon-arrow-right"></i>
          </el-button>

          <el-button
              v-else
              type="success"
              size="large"
              @click="SubmitAnswer"
              :loading="is_loading"
              :disabled="!isAllAnswered"
          >
            <i class="el-icon-check"></i> 提交答案
          </el-button>
        </div>
        <div v-if="!isAllAnswered" class="submit-tip">
          <i class="el-icon-warning-outline"></i> 请完成所有题目后再提交
        </div>
      </template>
    </el-card>
  </div>
</template>

<style scoped>
.quiz-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 32px 8px;
  background: linear-gradient(135deg, #e0e7ff 0%, #f5f7fa 100%);
}

.quiz-card {
  width: 100%;
  max-width: 600px;
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(58, 92, 255, 0.10), 0 1.5px 4px rgba(0,0,0,0.04);
  background: #fff;
  border: none;
  padding: 0 0 16px 0;
  position: relative;
  overflow: visible;
}

.quiz-header {
  margin-bottom: 18px;
  padding-top: 24px;
  text-align: center;
  position: relative;
}

.progress-container {
  margin-bottom: 10px;
}

.progress-bar {
  border-radius: 12px;
  background: #e3e8f7;
  box-shadow: 0 1px 4px rgba(106,130,251,0.08);
}

.timer-chip {
  display: inline-flex;
  align-items: center;
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  color: #fff;
  font-weight: 600;
  font-size: 16px;
  border-radius: 20px;
  padding: 4px 16px;
  margin: 0 auto 8px auto;
  box-shadow: 0 2px 8px rgba(106,130,251,0.10);
  gap: 8px;
  width: fit-content;
  position: relative;
}

.question-title {
  color: #2d3a4b;
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 0;
  text-align: center;
  letter-spacing: 1px;
}

.start-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 48px 0 32px 0;
  min-height: 320px;
  justify-content: center;
}

.start-title {
  font-size: 2rem;
  font-weight: 700;
  color: #6a82fb;
  margin-bottom: 12px;
  letter-spacing: 1px;
}

.start-desc {
  font-size: 1.1rem;
  color: #888;
  margin-bottom: 32px;
}

.start-btn {
  font-size: 1.2rem;
  padding: 12px 36px;
  border-radius: 24px;
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  color: #fff;
  border: none;
  box-shadow: 0 2px 8px rgba(106,130,251,0.10);
  transition: background 0.2s;
}
.start-btn:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
  color: #fff;
}

.question-content {
  margin-bottom: 32px;
  padding: 24px 20px;
  background: linear-gradient(90deg, #f8fafc 60%, #e0e7ff 100%);
  border-radius: 12px;
  border-left: 5px solid #6a82fb;
  box-shadow: 0 1px 4px rgba(106,130,251,0.06);
}

.question-text {
  color: #2d3a4b;
  font-size: 20px;
  line-height: 1.7;
  margin: 0;
  font-weight: 500;
}

.options-container {
  margin-bottom: 32px;
}

.options-group {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.option-item {
  margin: 4px 0;
  background: #f5f7fa;
  border-radius: 8px;
  transition: box-shadow 0.2s;
  font-size: 1.1rem;
  box-shadow: 0 1px 4px rgba(106,130,251,0.04);
}
.option-item .el-radio__input.is-checked + .el-radio__label {
  color: #6a82fb;
  font-weight: 600;
}
.option-label {
  margin-left: 8px;
  font-size: 18px;
  letter-spacing: 1px;
}

.navigation-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 24px;
  gap: 16px;
}

.navigation-buttons .el-button {
  min-width: 120px;
  font-size: 1.1rem;
  border-radius: 24px;
  padding: 10px 0;
  box-shadow: 0 1px 4px rgba(106,130,251,0.06);
  transition: background 0.2s;
}

.navigation-buttons .el-button--primary {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  color: #fff;
  border: none;
}
.navigation-buttons .el-button--primary:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
  color: #fff;
}

.navigation-buttons .el-button--success {
  background: linear-gradient(90deg, #43e97b 0%, #38f9d7 100%);
  color: #fff;
  border: none;
}
.navigation-buttons .el-button--success:hover {
  background: linear-gradient(90deg, #38f9d7 0%, #43e97b 100%);
  color: #fff;
}

.navigation-buttons .el-button--info {
  background: #e3e8f7;
  color: #6a82fb;
  border: none;
}
.navigation-buttons .el-button--info:hover {
  background: #d1d9f7;
  color: #6a82fb;
}

.submit-tip {
  margin-top: 18px;
  color: #fc5c7d;
  font-size: 1rem;
  text-align: center;
  display: flex;
  align-items: center;
  gap: 6px;
  justify-content: center;
  font-weight: 500;
}

@media (max-width: 768px) {
  .quiz-card {
    max-width: 98vw;
    padding: 0 0 8px 0;
  }
  .navigation-buttons {
    flex-direction: column;
    gap: 12px;
  }
  .navigation-buttons .el-button {
    width: 100%;
  }
  .question-content {
    padding: 16px 8px;
  }
  .timer-chip {
    font-size: 15px;
    padding: 3px 10px;
  }
}
</style>